package com.meixiang.view.Calendar;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;

import com.meixiang.entity.calaendar.CalendarResult;
import com.meixiang.entity.calaendar.ScheduleListBean;
import com.meixiang.tool.Tool;
import com.meixiang.util.DensityUtil;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * 作者：黑哥 on 2016/3/31 10:00
 * <p/>
 * 月显示图
 */
public class MonthDateView extends View {
    private Context mContext;
    //定义每行显示数目
    private static final int NUM_COLUMNS = 7;
    //定义每列显示数目
    private static final int NUM_ROWS = 6;
    //画笔
    private Paint mPaint;
    //定义默认日期的字体颜色 默认值为黑色

    //默认今天圆圈颜色
    private int mTodayColor = Color.parseColor("#e5e5e5");

    private int mSelectColor = Color.parseColor("#e9546b");

    private int mDayColor = Color.parseColor("#555555");
    //定义选中日期的字体颜色 默认值为白色
    private int mSelectDayColor = Color.parseColor("#000000");

    //定义选中日期的背景颜色 默认为白色
    private int mSelectBGColor = Color.parseColor("#ffffff");

    /**
     * 定义标注的颜色
     * 当前为还款日 color #ff8cbd
     */
    private int repaymentDateColor = Color.parseColor("#ff8cbd");
    /**
     * 定义标注的颜色
     * 当前为服务预约 color #86d978
     */

    private int serviceReservationColor = Color.parseColor("#86d978");

    /**
     * 定义标注的颜色
     * 当前为投资到期 color #8ca7ff
     */
    private int investExpiringColor = Color.parseColor("#8ca7ff");

    /**
     * 定义标注的颜色
     * 当前为备忘 color #ff8cbd
     */
    private int memoColor = Color.parseColor("#dccf66");

    //定义年月日
    private int mCurrYear, mCurrMonth, mCurrDay;

    //定义选中的年月日
    private int mSelYear, mSelMonth, mSelDay;

    //定义列 行 大小
    private int mColumnSize, mRowSize;
    //
    private DisplayMetrics mDisplayMetrics;

    //定义日期字体大小
    private int mDaySize = 10;

    //定义日期字体大小
    private int mToDaySize = 10;

    //日期控件 周控件
    private TextView tv_date, tv_week;

    //定义一个多少周显示
    private int weekRow;

    //定义一个 日期数组
    private int[][] daysString;

    //定义一个显示小圆圈
    private int mCircleRadius;


    private int mCircleWith;
    //日期的点击 回调接口

    private DateClick dateClick;
    //定义一个选中的日期的颜色
    private int mCircleColor = Color.parseColor("#ff0000");

    private List<CalendarResult> mCalendarResult;

    private List<ScheduleListBean> mScheduleList =new ArrayList<>();

    private String yearData, monthData;


    private boolean isOnClick = false;

    //
    private List<ScheduleListBean> mDayList = null;
    //定义一个日程类型
    private List<ScheduleListBean> mStyleList = new ArrayList<>();

    private boolean isSelect = false;


    private int weekNumber;


    /**
     * 构造方法
     */
    public MonthDateView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        mDisplayMetrics = getResources().getDisplayMetrics();
        //日历
        Calendar calendar = Calendar.getInstance();

        mPaint = new Paint();
        //画年月日
        mCurrYear = calendar.get(Calendar.YEAR);
        mCurrMonth = calendar.get(Calendar.MONTH);
        mCurrDay = calendar.get(Calendar.DATE);
        //设置年月日
        setSelectYearMonth(mCurrYear, mCurrMonth, mCurrDay);
    }

    /**
     * 测量
     */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    /**
     * 画笔
     * <p/>
     * 画随之对应的控件
     */
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //初始化
        initSize();
        //定义天数组
        daysString = new int[6][7];
        //画每月日期的字体大小
        mPaint.setTextSize(mDaySize * mDisplayMetrics.scaledDensity);
        //定义一个日期
        String dayString;
        //定义几月和多少周
        int mYearNumber = DataUtils.getMonthDays(mSelYear, mSelMonth);
        //到当前月的天数
        int mMonthDays = DataUtils.getMonthDays(mSelYear, mSelMonth);
        //得到当前是周几
        weekNumber = DataUtils.getFirstDayWeek(mSelYear, mSelMonth);
        //循环为赋值 绘画圆
        for (int day = 0; day < mMonthDays; day++) {
            //因为是重0开始的 所以+1 然后转换为String类型
            dayString = (day + 1) + "";

            //定义当前的月的多少行
            int column = (day + weekNumber - 1) % 7;
            int row = (day + weekNumber - 1) / 7;
            daysString[row][column] = day + 1;
            int startX = (int) (mColumnSize * column + (mColumnSize - mPaint.measureText(dayString)) / 2);
            int startY = (int) (mRowSize * row + mRowSize / 2 - (mPaint.ascent() + mPaint.descent()) / 2);
            mPaint.setStyle(Paint.Style.FILL); //设置实心
            //定义圆环开始位置
            int CircleX = (int) (mColumnSize * column + mColumnSize / 2);
            int CircleY = (int) (mRowSize * row + mRowSize / 2);
            if (dayString.equals(mCurrDay + "") && mSelYear == mCurrYear && mSelMonth == mCurrMonth) {
                //绘制背景色 圆形
                int startRecX = mColumnSize * column;
                int startRecY = mRowSize * row;
                int endRecX = startRecX + mColumnSize;
                int endRecY = startRecY + mRowSize;
                //定义圆 的圆心X轴坐标
                int centreX = (endRecX - startRecX) / 2;
                //定义圆 的圆心Y轴坐标
                int centreY = (endRecY - startRecY) / 2;
                //定义圆 圆环的半径
                //定义圆 半径
                mCircleWith = DensityUtil.dip2px(mContext, 1);
                int centre = centreY - mCircleWith * 4;
                //设置圆的颜色
                mPaint.setColor(mTodayColor);
                mPaint.setAntiAlias(true);
                mPaint.setStyle(Paint.Style.STROKE); //设置空心
                mPaint.setStrokeWidth(mCircleWith); //设置圆环的宽度
                canvas.drawCircle(CircleX, CircleY, centre, mPaint);
                weekRow = row + 1;
            }
            if (dayString.equals(mSelDay + "")) {
                int columns = (day + weekNumber - 1) % 7;
                int rows = (day + weekNumber - 1) / 7;
                int X = (int) (mColumnSize * columns + mColumnSize / 2);
                int Y = (int) (mRowSize * rows + mRowSize / 2);
                int startRecX = mColumnSize * columns;
                int startRecY = mRowSize * rows;
                int endRecY = startRecY + mRowSize;
                int centreY = (endRecY - startRecY) / 2;
                int centre = centreY - mCircleWith * 4;
                if (isOnClick = true) {
                    mPaint.setColor(mSelectColor);
                } else {
                    mPaint.setColor(mDayColor);
                }
                mPaint.setStrokeWidth(mCircleWith); //设置圆环的宽度
                mPaint.setStyle(Paint.Style.STROKE); //设置空心
                canvas.drawCircle(CircleX, CircleY, centre, mPaint);

            } else if (dayString.equals(mCurrDay + "") && mCurrDay != mSelDay && mCurrMonth == mSelMonth) {
                mPaint.setColor(mDayColor);
            } else {
                mPaint.setColor(mDayColor);
            }
            mPaint.setStyle(Paint.Style.FILL); //设置实心
            /**
             * 如果当前是today
             *
             * 设置dayString为今天
             * */
            if (dayString.equals(mCurrDay + "") && mSelYear == mCurrYear && mSelMonth == mCurrMonth) {
                dayString = "今天";
                //- DensityUtil.dip2px(mContext, 2)
                startX = (int) (mColumnSize * column + (mColumnSize - mPaint.measureText(dayString)) / 2);
            }


            canvas.drawText(dayString, startX, startY, mPaint);
            if (tv_date != null) {
                tv_date.setText(this.mSelYear + "年" + (mSelMonth + 1) + "月");
            }

            if (tv_week != null) {
                tv_week.setText("第" + weekRow + "周");
            }
        }
        /**
         * 写在循环外面
         * 为日期下面赋值不同的点
         * */
        drawCircleDot(canvas);
    }

    private getDayLisy mGetDayLisy;

    public void onGetDayLisyListener(getDayLisy mGetDayLisy) {
        this.mGetDayLisy = mGetDayLisy;
    }


    /**
     * 画小圆点
     */
    private void drawCircleDot(Canvas canvas) {
        //得到当前是周几
        if (yearData != null && monthData != null) {
//            int mWeekNumber = DataUtils.getFirstDayWeek(Integer.valueOf(yearData), Integer.valueOf(monthData)-1);
            for (int i = 0; i < mCalendarResult.size(); i++) {
                int day = Integer.valueOf(Tool.toDay(mCalendarResult.get(i).getRemindTime())) - 1;
                int column = (day + weekNumber - 1) % 7;
                int mRow = (day + weekNumber - 1) / 7;
                mCircleRadius = DensityUtil.dip2px(mContext, 2);
                float iconY;

                float iconX = (float) (mColumnSize * column + mColumnSize * 0.5);
                String Year = mCurrYear + "";

                String Month = mCurrMonth + 1 + "";

                String Days = mCurrDay + "";

                String mMonth = mSelMonth + 1 + "";

                if (yearData.equals(Year) && monthData.equals(Month) && String.valueOf(day).equals(Days)) {
                    iconY = (float) (mRowSize * mRow + mRowSize + DensityUtil.dip2px(mContext, 4));
                } else {
                    iconY = (float) (mRowSize * mRow + mRowSize);
                }
                float iconX_base = (float) (mColumnSize * column);

                float iconX_base2 = (float) (mColumnSize * column + mColumnSize * 0.1);

                float iconX_2 = (float) (mColumnSize * column + mColumnSize * 0.2);

                if (yearData.equals(mSelYear + "") && monthData.equals(mMonth)) {
                    Tool.toDay(mCalendarResult.get(i).getRemindTime());
                    mDayList = mCalendarResult.get(i).getScheduleList();
//
//                    if (mSelDay == Integer.valueOf(Tool.toDay(mCalendarResult.get(i).getRemindTime()))) {
//                        for (int s = 0; s < mDayList.size(); s++) {
//                            if (mGetDayLisy != null) {
//                                mGetDayLisy.getDayData(mDayList);
//                            }
//                        }


                    int color = 0;
                    mScheduleList.clear();
                    mScheduleList.addAll(mCalendarResult.get(i).getScheduleList());

                    if (mSelDay == Integer.valueOf(Tool.toDay(mCalendarResult.get(i).getRemindTime()))) {
                        for (int s = 0; s < mScheduleList.size(); s++) {
                            if (mGetDayLisy != null) {
                                mGetDayLisy.getDayData(mScheduleList);
                            }
                        }
                    }

                    mStyleList.clear();
                    mStyleList.addAll(mCalendarResult.get(i).getScheduleList());


                    for (int d = 0; d < mStyleList.size() - 1; d++) {
                        for (int j = mStyleList.size() - 1; j > d; j--) {
                            if (mStyleList.get(j).getScheduleType().equals(mStyleList.get(d).getScheduleType())) {
                                mStyleList.remove(j);
                            }
                        }
                    }



                    for (int a = 0; a < mStyleList.size(); a++) {
                        if (mStyleList.get(a).getScheduleType().equals("LOAN")) {
                            color = repaymentDateColor;
                        } else if (mStyleList.get(a).getScheduleType().equals("MEMOS")) {
                            color = memoColor;
                        } else if (mStyleList.get(a).getScheduleType().equals("FORESPOKE")) {
                            color = serviceReservationColor;
                        } else if (mStyleList.get(a).getScheduleType().equals("EXPIRE")) {
                            color = investExpiringColor;
                        }
                        if (mStyleList.size() == 1) {
                            iconX = (float) (iconX_base + mColumnSize * 0.5);
                        }
                        if (mStyleList.size() == 2) {
                            iconX = iconX_2 += mColumnSize * 0.2;
                        }
                        if (mStyleList.size() == 3) {
                            iconX = iconX_base2 += mColumnSize * 0.2;
                        }
                        if (mStyleList.size() == 4) {
                            iconX = iconX_base += mColumnSize * 0.2;
                        }
                        drawdot(iconX, iconY, color, canvas);
                    }
                }
            }

        }
    }

    private void drawdot(float iconX, float iconY, int color, Canvas canvas) {
        mPaint.setColor(color);
        mPaint.setAntiAlias(true);
        canvas.drawCircle(iconX, iconY, mCircleRadius, mPaint);
    }


    @Override
    public boolean performClick() {
        return super.performClick();
    }

    private int downX = 0, downY = 0;

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int eventCode = event.getAction();
        switch (eventCode) {
            case MotionEvent.ACTION_DOWN:
                downX = (int) event.getX();
                downY = (int) event.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                break;
            case MotionEvent.ACTION_UP:
                int upX = (int) event.getX();
                int upY = (int) event.getY();
                if (Math.abs(upX - downX) < 10 && Math.abs(upY - downY) < 10) {//点击事件
                    performClick();
                    doClickAction((upX + downX) / 2, (upY + downY) / 2);
                }
                break;
        }
        return true;
    }

    /**
     * 初始化列宽行高
     */
    private void initSize() {
        mColumnSize = getWidth() / NUM_COLUMNS;
        mRowSize = getHeight() / NUM_ROWS;
    }

    /**
     * 设置年月
     *
     * @param year
     * @param month
     */
    private void setSelectYearMonth(int year, int month, int day) {
        mSelYear = year;
        mSelMonth = month;
        mSelDay = day;
    }

    /**
     * 执行点击事件
     *
     * @param x
     * @param y
     */
    private void doClickAction(int x, int y) {
        int row = y / mRowSize;
        int column = x / mColumnSize;
        setSelectYearMonth(mSelYear, mSelMonth, daysString[row][column]);
        invalidate();
        //执行activity发送过来的点击处理事件
        if (dateClick != null) {
            dateClick.onClickOnDate();
            isOnClick = true;

        }
    }

    /**
     * 左点击，日历向后翻页
     */
    public void onLeftClick() {
        int year = mSelYear;
        int month = mSelMonth;
        int day = mSelDay;
        if (month == 0) {//若果是1月份，则变成12月份
            year = mSelYear - 1;
            month = 11;
        } else if (DataUtils.getMonthDays(year, month) == day) {
            //如果当前日期为该月最后一点，当向前推的时候，就需要改变选中的日期
            month = month - 1;
            day = DataUtils.getMonthDays(year, month);
        } else {
            month = month - 1;
        }
        setSelectYearMonth(year, month, day);
        invalidate();
    }

    /**
     * 右点击，日历向前翻页
     */
    public void onRightClick() {
        int year = mSelYear;
        int month = mSelMonth;
        int day = mSelDay;
        if (month == 11) {//若果是12月份，则变成1月份
            year = mSelYear + 1;
            month = 0;
        } else if (DataUtils.getMonthDays(year, month) == day) {
            //如果当前日期为该月最后一点，当向前推的时候，就需要改变选中的日期
            month = month + 1;
//            day = DateUtils.getMonthDays(year, month);
            day = DataUtils.getMonthDays(year, month);
        } else {
            month = month + 1;
        }
        setSelectYearMonth(year, month, day);
        invalidate();
    }

    /**
     * 获取选择的年份
     *
     * @return
     */
    public int getmSelYear() {
        return mSelYear;
    }

    /**
     * 获取选择的月份
     *
     * @return
     */
    public int getmSelMonth() {
        return mSelMonth;
    }

    /**
     * 获取选择的日期
     *
     * @param
     */
    public int getmSelDay() {
        return this.mSelDay;
    }

    /**
     * 普通日期的字体颜色，默认黑色
     *
     * @param mDayColor
     */
    public void setmDayColor(int mDayColor) {
        this.mDayColor = mDayColor;
    }

    /**
     * 选择日期的颜色，默认为白色
     *
     * @param mSelectDayColor
     */
    public void setmSelectDayColor(int mSelectDayColor) {
        this.mSelectDayColor = mSelectDayColor;
    }

    /**
     * 选中日期的背景颜色，默认蓝色
     *
     * @param mSelectBGColor
     */
    public void setmSelectBGColor(int mSelectBGColor) {
        this.mSelectBGColor = mSelectBGColor;
    }

    /**
     * 当前日期不是选中的颜色，默认红色
     *
     * @param mCurrentColor
     */
    public void setmCurrentColor(int mCurrentColor) {
        this.serviceReservationColor = mCurrentColor;
    }

    /**
     * 日期的大小，默认18sp
     *
     * @param mDaySize
     */
    public void setmDaySize(int mDaySize) {
        this.mDaySize = mDaySize;
    }

    /**
     * 设置显示当前日期的控件
     *
     * @param tv_date 显示日期
     * @param tv_week 显示周
     */
    public void setTextView(TextView tv_date, TextView tv_week) {
        this.tv_date = tv_date;
        this.tv_week = tv_week;
        invalidate();
    }

    /**
     * 设置数据
     */

    public void setCalendarList(List<CalendarResult> mCalendarResult, String year, String month) {
        this.mCalendarResult = mCalendarResult;
        this.yearData = year;
        this.monthData = month;
        invalidate();

    }

    /***
     * 设置圆圈的半径，默认为6
     *
     * @param mCircleRadius
     */
    public void setmCircleRadius(int mCircleRadius) {
        this.mCircleRadius = mCircleRadius;
    }

    /**
     * 设置圆圈的半径
     *
     * @param mCircleColor
     */
    public void setmCircleColor(int mCircleColor) {
        this.mCircleColor = mCircleColor;
    }

    /**
     * 设置日期的点击回调事件
     *
     * @author shiwei.deng
     */
    public interface DateClick {
        public void onClickOnDate();

    }


    /**
     * 设置日期点击事件
     *
     * @param dateClick
     */
    public void setDateClick(DateClick dateClick) {
        this.dateClick = dateClick;
    }

    /**
     * 跳转至今天
     */
    public void setTodayToView() {
        setSelectYearMonth(mCurrYear, mCurrMonth, mCurrDay);
        invalidate();

    }

    /**
     * 当前的年份
     *
     * @return
     */
    public int getmCurrYear() {
        return mCurrYear;
    }

    /**
     * 当前月份
     *
     * @return
     */
    public int getmCurrMonth() {
        return mCurrMonth;
    }

    /**
     * 当前日期
     *
     * @param
     */
    public int getmCurrDay() {
        return mCurrDay;
    }


    //得到数据
    public interface getDayLisy {
        public void getDayData(List<ScheduleListBean> mDayList);
    }

}